package com.kdgc.power.business.service;

import com.kdgc.power.business.entity.SysMenu;
import com.kdgc.power.business.mapper.SysMenuMapper;
import com.kdgc.power.common.util.StringUtil;
import com.kdgc.power.fw.bean.TreeNode;
import com.kdgc.power.fw.service.BaseService;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuService extends BaseService<SysMenu> {
    @Resource
    private SysMenuMapper sysMenuMapper;

    public List<TreeNode> findAll(String flag) {
        return sysMenuMapper.getTreeList(flag);
    }

    public List<TreeNode> buildTree(String parentCode, String prefix,List<TreeNode> dataList) {
        List<TreeNode> parents = dataList.stream().filter(d ->
                parentCode.equals(d.getPCode())).collect(Collectors.toList()
        );
        for (TreeNode parent : parents) {
            if ("root".equals(parent.getPCode())) {
                parent.setPath("/" + parent.getCode());
            } else {
                parent.setPath(prefix + "/" + parent.getCode());
            }
            parent.setChildren(buildTree(parent.getCode(), parent.getPath(),dataList));
        }
        return parents;
    }

    public List<TreeNode> getTree(String flag) {
        List<TreeNode> all = findAll(flag);
        return buildTree("root","/", all);
    }


    public boolean saveWithChildren(SysMenu sysMenu) {
        Integer menuId = sysMenu.getMenuId();
        if (StringUtil.isNotEmpty(menuId)) {
            SysMenu oldMenu = getEntity(menuId);
            LambdaQuery<SysMenu> query = sysMenuMapper.createLambdaQuery();
            List<SysMenu> children = query.andEq(SysMenu::getPmenuCode, oldMenu.getMenuCode()).andEq(SysMenu::getIsUse, "Y").select();
            children.forEach(child->{
                child.setPmenuCode(sysMenu.getMenuCode());
                saveOrUpdate(child);
            });
        }
        return saveOrUpdate(sysMenu);
    }

}